//
//  KKLoginViewController.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/21.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKLoginViewController.h"

#import "KKNetworkRequest+V1.h"

#import "KKQRCodeViewController.h"
#import "KKNavigationController.h"

#import <UserNotifications/UserNotifications.h>

#import "KKTopAlertView.h"
#import "AppDelegate.h"

#import "KKImagePickerManager.h"
#import "SVProgressHUD.h"


@interface KKLoginViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) NSString *ticket;
@property (nonatomic, strong) UIImage *headimg;
@end

@implementation KKLoginViewController

- (void)loadView {
    [super loadView];
    
    self.img_headimg.layer.cornerRadius = CGRectGetWidth(self.img_headimg.bounds)/2.0;
    self.img_headimg.layer.masksToBounds = true;
    self.img_headimg.layer.borderColor = [UIColor colorWithRed:61/255.0 green:83/255.0 blue:114/255.0 alpha:0.8].CGColor;
    self.img_headimg.layer.borderWidth = 5;
    
    self.btn_bind.layer.cornerRadius = 32.5;
    self.btn_bind.layer.masksToBounds = true;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //  第一次调用，以获得网络获取权限
    KKNetworkRequest *request = [KKNetworkRequest request_ping];
    [KKNetworking sendRequest: request responseCallBack: nil];
}

- (void)dealloc {
    NSLog(@"KKLoginViewController");
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.txf_nickname resignFirstResponder];
}

#pragma mark - UITextFieldDelegate methos
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return true;
}

#pragma mark - Action methods

-(IBAction)action_bind:(id)sender {
    //  1、微信授权获取code
    //  2、调用扫码功能，获取公司ticket
    
    if (self.txf_nickname.text.length == 0) {
        [self kk_showTopAlertViewWithMessage: @"请填写客服名称"];
        return;
    }
    
    if (self.headimg == nil) {
        [self kk_showTopAlertViewWithMessage: @"请先上传头像"];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
                [weakSelf private_getCompanyInfo];
                return;
            }
            [weakSelf kk_showTopAlertViewWithMessage: @"请开启推送"];
        }];
    }];
}

- (IBAction)action_headimg:(id)sender {
    //  获取头像
    
    [self.txf_nickname resignFirstResponder];
    
    __weak typeof(self) weakSelf = self;
    KKImagePickerManager *manager = [KKImagePickerManager kk_defaultManager];
    manager.maxLimit = 1;
    manager.edit = true;
    manager.resultBlock = ^(NSArray *images) {
        weakSelf.img_headimg.image = [images firstObject];
        weakSelf.headimg = [images firstObject];
    };
    [manager kk_takePicture];
    
}

#pragma mark - Private methods

- (void)private_getCompanyInfo {
    //  通过扫描二维码获取公司的授权信息
    
    __weak typeof(self) weakSelf = self;
    KKQRCodeViewController *codeViewController = [KKQRCodeViewController new];
    codeViewController.resultBlock = ^(NSDictionary *reslut){
        if ([reslut isKindOfClass: [NSDictionary class]]) {
            weakSelf.ticket = reslut[@"ticket"];
            [weakSelf private_sendUploadImageRequest];
        }
    };
    
    KKNavigationController *rootViewController = [[KKNavigationController alloc] initWithRootViewController: codeViewController];
    [self presentViewController: rootViewController animated: true completion: nil];
}

- (void)private_sendUploadImageRequest {
    
    __weak typeof(self) weakSelf = self;
    [SVProgressHUD showWithStatus: nil];
    
    [KKNetworking uploadImage: self.headimg parmeters: nil progress: nil responseCallBack:^(id response, NSString *error) {
        
        if (error) {
            [SVProgressHUD dismiss];
            [weakSelf kk_showTopAlertViewWithMessage: error];
            return;
        }
        
        if ([response isKindOfClass: [NSString class]]) {
            //  上传成功
            NSString *imgPath = (NSString*)response;
            [weakSelf private_sendLoginRequestWithImagePath: imgPath];
        }
    }];
}

- (void)private_sendLoginRequestWithImagePath:(NSString*)imagePath {
    NSString *deviceId = [(AppDelegate*)[UIApplication sharedApplication].delegate pushToken];
    
    NSString *nickName = self.txf_nickname.text;
    
    __weak typeof(self) weakSelf = self;
    KKNetworkRequest *request = [KKNetworkRequest request_loginWithTicketId: self.ticket deviceId: deviceId nickName: nickName headimg: imagePath];
    [KKNetworking sendRequest: request showStatus: false responseCallBack:^(id response, NSString *error) {
        
        if (error) {
            [SVProgressHUD dismiss];
            [weakSelf kk_showTopAlertViewWithMessage: error];
            return;
        }
        if ([response isKindOfClass: [NSDictionary class]]) {
            [KKUser loginWithJson: response nickName: nickName headImg: imagePath];
        }
        [SVProgressHUD dismiss];
    }];
}
@end
